package com.seng.ossservice.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.seng.ossservice.entity.OssEntity;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Component
public class AliOSSUtils {
    @Autowired
    private OssEntity ossEntity;

    public void createBucket() {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossEntity.getEndpoint(), ossEntity.getAccessKeyId(), ossEntity.getAccessKeySecret());

        // 创建存储空间。
        ossClient.createBucket(ossEntity.getBucketName());

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    public String uploadImgFile(MultipartFile file) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossEntity.getEndpoint(), ossEntity.getAccessKeyId(), ossEntity.getAccessKeySecret());

        // 添加 ContentType
        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 直接设置 content_type  解决直接下载无法预览效果

        objectMetadata.setContentType("image/png");
        //String pathUrl = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        try {
            PutObjectResult result = ossClient.putObject(ossEntity.getBucketName(), "meizi.png", file.getInputStream(), objectMetadata);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭OSSClient。
        ossClient.shutdown();

        return "https://" + ossEntity.getBucketName() + "." + "oss-cn-shanghai.aliyuncs.com" + "/" + file.getOriginalFilename();
    }

    public void downloadImgFile() {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossEntity.getEndpoint(), ossEntity.getAccessKeyId(), ossEntity.getAccessKeySecret());

        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(ossEntity.getBucketName(), "meizi.jpg");

        // 读取文件内容。
        System.out.println("Object content:");
        BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
        while (true) {
            String line = null;
            try {
                line = reader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (line == null) {
                break;
            }

            System.out.println("\n" + line);
        }
        // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    public void downloadImgToLocal() {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossEntity.getEndpoint(), ossEntity.getAccessKeyId(), ossEntity.getAccessKeySecret());

        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        ossClient.getObject(new GetObjectRequest(ossEntity.getBucketName(), "meizi.jpg"), new File("E:\\meizi.jpg"));

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * 获得url链接
     * @return
     */
    public String getUrl() {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossEntity.getEndpoint(), ossEntity.getAccessKeyId(), ossEntity.getAccessKeySecret());
        // 生成URL
        URL url = ossClient.generatePresignedUrl(ossEntity.getBucketName(), ossEntity.getAccessKeyId(), expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    public String upload(MultipartFile file) {

        //获取阿里云存储相关常量
        String endPoint = ossEntity.getEndpoint();
        String accessKeyId = ossEntity.getAccessKeyId();
        String accessKeySecret = ossEntity.getAccessKeySecret();
        String bucketName = ossEntity.getBucketName();

        String uploadUrl = null;

        try {
            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            if (!ossClient.doesBucketExist(bucketName)) {
                //创建bucket
                ossClient.createBucket(bucketName);
                //设置oss实例的访问权限：公共读
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }

            //获取上传文件流
            InputStream inputStream = file.getInputStream();

            //构建日期路径：avatar/2020/07/31/文件名
            String datePath = new DateTime().toString("yyyy/MM/dd");

            //文件名：uuid.扩展名
            String original = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString().replaceAll("-","");
            String fileType = original.substring(original.lastIndexOf("."));
            String newName = fileName + fileType;

            fileName = datePath+"/"+newName;


            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setObjectAcl(CannedAccessControlList.PublicRead);
            //objectMetadata.setContentLength(inputStream.available());
            //objectMetadata.setCacheControl("no-cache");
            //objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));

            //文件上传至阿里云
            ossClient.putObject(bucketName, fileName, inputStream,objectMetadata);

            // 关闭OSSClient。
            ossClient.shutdown();

            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
            uploadUrl = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString();

            //获取url地址
            //uploadUrl = "https://" + bucketName + "." + endPoint + "/" + fileName;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return uploadUrl.substring(0, uploadUrl.indexOf("?"));
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }
}
